from loguru import logger
from com.arcfox.middleware import async_mysql_middleware as db
from com.arcfox.school.processor.base_processor import BaseProcessor
from com.arcfox.school.util import jzy_decrypt_util


class MajorScoreProcessor(BaseProcessor):
    def __init__(self):
        super().__init__()
        self.table_name = "tb_major_score"
        self.kemu_item = {
            "1": "文科",
            "2": "理科",
            "3": "综合"
        }

    async def store_major_score(self, task, result_json):
        data_list = result_json['data']
        for data in data_list:
            if isinstance(data, str):
                data = data_list[data]
            province = data['provincesName']
            score_year = data['year']
            subject_item = self.kemu_item[str(data['kemu'])] if str(data['kemu']) in self.kemu_item else data['kemu']
            batch_name = data['batch_name']
            major_name = data['major_title']
            min_score = jzy_decrypt_util.decrypt_font(data['min_score'])
            min_rank = jzy_decrypt_util.decrypt_font(data['min_rank'])
            enroll_count = jzy_decrypt_util.decrypt_font(data['luqu_count'])
            school_name = task['school_name']
            data = {
                "province": province, "score_year": score_year,
                "subject_item": subject_item, "batch_name": batch_name,
                "major_name": major_name, "min_score": min_score,
                "min_rank": min_rank, "enroll_count": enroll_count,
                "university_name": school_name, "university_uid": self.generate_school_uid(school_name)
            }
            mapping = db.MysqlMapping(self.table_name)
            check_result = await self.check_exist(mapping, data)
            if check_result:
                #logger.info("数据已存在, 更新数据")
                #await mapping.update(data, {"id": check_result})
                logger.info("数据已存在, 不操作")
            else:
                logger.info("数据不存在, 插入数据")
                data['lastupdate_time'] = "now()"
                await mapping.insert(data)

    async def check_exist(self, mapping, data):
        condition = {
            "university_uid": data['university_uid'],
            "province": data['province'],
            "score_year": data['score_year'],
            "batch_name": data['batch_name'],
            "major_name": data['major_name'],
        }
        result = await mapping.query(condition, ["id"])
        if result:
            return result[0][0]


if __name__ == "__main__":
    MajorScoreProcessor().parse_error_data("")
